package com.vip.zuul.ztools;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.vip.zuul.configuration.VIPZuulRouteLocator;
import com.vip.zuul.service.IRequestCheckService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.Route;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import javax.servlet.http.HttpServletRequest;

/**
 * 限流过滤器
 *
 * @author richard_xsyao
 * @date 2018/10/16 17:57
 * Description: This filter used to deal request's frequency with different rules
 */
public class FrequencyPreFilter extends ZuulFilter {

    @Autowired
    private VIPZuulRouteLocator vipZuulRouteLocator;
    
    @Autowired
    private IRequestCheckService vipFilterService;

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    /**
     * order值越小，优先级越高
     * @return
     */
    @Override
    public int filterOrder() {
        return 1;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        String prefixPath  = request.getServletPath();
        Route matchRoute = vipZuulRouteLocator.getMatchingRoute(prefixPath);
        if(matchRoute != null) {
            // Get match route's id for next deal
            String routeNodeId = matchRoute.getId();
            // Get configuration for this route node
            boolean result = vipFilterService.checkRequestFrequence(request);
            if(!result) {
                JSONObject response = new JSONObject();
                response.put("success", false);
                response.put("code", 401);
                response.put("messages", "接口请求过于频繁");
                ctx.setResponseBody(JSON.toJSONString(response));
            }
        } else {
            JSONObject response = new JSONObject();
            response.put("success", false);
            response.put("code", 401);
            response.put("messages", "未找到匹配路由");
            ctx.setResponseBody(JSON.toJSONString(response));
        }
        return null;
    }
}